package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.commons.ServerResponce;
import com.chixing.commons.ServerResponse;
import com.chixing.mapper.UsersMapper;
import com.chixing.pojo.CustomerTokenDTO;
import com.chixing.pojo.Users;
import com.chixing.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaotao
 * @since 2022-10-12
 */
@Service
public class UsersServiceImpl implements IUsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public ServerResponce login(Users users) {

        //1. DB 验证用户账号与密码
        QueryWrapper<Users> wrapper =  new QueryWrapper<>();
        wrapper.eq("user_telno",users.getUserTelno());
        wrapper.eq("user_pwd",users.getUserPwd());

        Users loginUser = usersMapper.selectOne(wrapper);
        System.out.println("1.在DB中查询到的登录账户：" + loginUser);

        if(loginUser !=null) {

            //2. JWT创建token
            CustomerTokenDTO userTokenDTO = new CustomerTokenDTO(loginUser.getUserId(),loginUser.getUserNickname());
            System.out.println("2.userTokenDTO" + userTokenDTO);

            String token = TokenUtil.sign(userTokenDTO);
            System.out.println("3.service token:" + token);

            return ServerResponce.success("登录成功", token);
        }else
            return ServerResponce.fail("登录失败",null);

    }


    @Override
    public Users selectById(Integer userId) {
        Users user = usersMapper.selectById(userId);
        return user;
    }

    @Override
    public ServerResponse getById(Integer userId) {
        Users user = usersMapper.selectById(userId);
        if(user!=null)
            return ServerResponse.success("查询用户成功", user);
        else
            return ServerResponse.fail("查询用户失败", null);
    }

    @Override
    public List<Users> getAll() {
        return usersMapper.selectList(null);
    }

    @Override
    public ServerResponse save(Users users) {
        int rows = usersMapper.insert(users);
        if(rows > 0)
            return ServerResponse.success("查询成功！",users);
        else
            return ServerResponse.fail("查询失败！请重试！",null);
    }

    @Override
    public Users getUpdateUsersById(Integer userId) {
        return usersMapper.selectById(userId);
    }

    @Override
    public ServerResponse updateUser(Users users) {
        int rows = usersMapper.updateById(users);
        if (rows !=0)
            return ServerResponse.success("修改用户成功", users);
        return ServerResponse.fail("修改用户失败", null);
    }

}
